<template>
  <div class="app-container calendar-list-container">
      <template>
        <el-tabs @tab-click="switchTab">
          <el-tab-pane label='信息管理' name='userManager'/>
          <el-tab-pane label='密码管理' name='passwordManager'/>
        </el-tabs>
      </template>
      <el-row>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form :model="userForm"
                     :rules="passwordRule"
                     ref="user"
                     label-width="100px"
                     v-if="switchStatus==='userManager'"
                     class="demo-ruleForm">
              <el-form-item label="用户名"
                            prop="username">
                <el-input type="text"
                          v-model="userForm.username"
                          disabled></el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="userForm.phone" placeholder="验证码登录使用"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="userForm.email" placeholder="验证码登录使用"></el-input>
              </el-form-item>
              <el-form-item label="头像" prop="avatar">
                <el-upload
                  class="avatar-uploader"
                  action=""
                  :http-request="upload"
                  :auto-upload="true"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                  <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
              <el-form-item>
                <el-button type="primary"
                           @click="submitForm('user')">提交
                </el-button>
                <el-button @click="resetForm('user')">重置</el-button>
              </el-form-item>
            </el-form>
            <el-form :model="userForm"
                     :rules="passwordRule"
                     ref="userForm"
                     label-width="100px"
                     v-if="switchStatus==='passwordManager'"
                     class="demo-ruleForm">
              <el-form-item label="原密码"
                            prop="password">
                <el-input type="password"
                          v-model="userForm.password"
                          auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="密码"
                            prop="newpassword1">
                <el-input type="password"
                          v-model="userForm.newpassword1"
                          auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="确认密码"
                            prop="newpassword2">
                <el-input type="password"
                          v-model="userForm.newpassword2"
                          auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary"
                           @click="submitForm('userForm')">提交
                </el-button>
                <el-button @click="resetForm('user')">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
  </div>
</template>


<script>
  import {mapState} from 'vuex'
  import {fileApi} from "../../../http/modules/file"
  import {userApi} from "../../../http/modules/user"

  export default {
    data() {
      var validatePass = (rule, value, callback) => {
        if (this.userForm.password !== '') {
          if (value !== this.userForm.newpassword1) {
            callback(new Error('两次输入密码不一致!'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      return {
        switchStatus: '',
        avatarUrl: '',
        show: false,
        // headers: {
        //   Authorization: 'Bearer ' + store.getters.access_token
        // },
        userForm: {
          userId: '',
          username: '',
          password: '',
          newpassword1: '',
          newpassword2: '',
          avatar: '',
          phone: '',
          email: ''
        },
        passwordRule: {
          password: [{required: true, min: 6, message: '原密码不能为空且不少于6位', trigger: 'change'}],
          newpassword1: [{required: false, min: 6, message: '不少于6位', trigger: 'change'}],
          newpassword2: [{required: false, validator: validatePass, trigger: 'blur'}]
        },
        imageUrl: ''
      }
    },
    created() {
      this.userForm = this.userInfo
      this.imageUrl = 'http://182.92.235.211:8080/' + this.userInfo.avatar
      this.switchStatus = 'userManager'
    },
    computed: {
      ...mapState({
        userInfo: state => state.user.userInfo
      }),
    },
    methods: {
      switchTab(tab, event) {
        this.switchStatus = tab.name
      },
      submitForm(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            userApi.update(this.userForm).then(res => {
              this.$message.success('用户信息更新成功')

            }).catch(error => {
              this.$message.error('用户信息更新失败')
            })
          } else {
            return false
          }
        })
      },
      resetForm(formName) {
        this.$refs[formName].resetFields()
      },
      upload(item) {
        let files = []
        files.push(item.file)
        let param = {userId: this.$store.getters.userInfo.userId}
        fileApi.uploadAvatar(param, files).then(res => {
          this.imageUrl = 'http://182.92.235.211:8080/' + res.msg
          this.userForm.avatar = res.msg
        }).console.log(error => {
          console.log(error)
          this.$message.success('上传失败')
        })

      },
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      }
    }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px!important;
    color: #8c939d!important;
    width: 178px!important;
    height: 178px!important;
    line-height: 178px!important;
    text-align: center!important;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
